package spring.boot.btc.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spring.boot.btc.common.BlockProperty;
import spring.boot.btc.model.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 挖矿
 */
@Slf4j
@Service
public class MiningService {

    @Autowired
    private BlockService blockService;

    public void mining() {
        Wallet wallet = Wallet.getInstance();

        //创建挖矿 系统奖励的交易
        TransactionInput input = TransactionInput.getSystemInput();
        List<TransactionInput> inputList = new ArrayList<>();
        inputList.add(input);
        TransactionOutput output = new TransactionOutput(wallet.getPublicKeyString(), input.getMoney());
        List<TransactionOutput> outputList = new ArrayList<>();
        outputList.add(output);
        Transaction transaction = new Transaction(inputList, outputList);

        //获取最后一块区块
        Block lastBlock = BlockProperty.blockList.get(BlockProperty.blockList.size() - 1);

        //定义初始工作量
        long nonce = 1L;

        String lastBlockHash = lastBlock.getHash();
        long version = lastBlock.getVersion() + 1L;
        //开始挖矿（开始进行计算）
        while (true) {
            Block block = new Block(lastBlockHash, version, nonce, transaction, System.currentTimeMillis());
            String hash = block.getHash();
            if (hash.startsWith("0000")) {
                log.info("本次挖矿成功，计算次数为:[{}],hash:[{}......]", nonce, hash.substring(0, 20));
                blockService.addToLast(block, 1);
                break;
            }
            nonce++;
        }
    }


}
